//
//  PKRequestTool.m
//  Panku
//
//  Created by 王旭 on 16/9/14.
//  Copyright © 2016年 Monster. All rights reserved.
//

#import "PKRequestTool.h"
#import <AliyunOSSiOS/OSSService.h>
#import <AliyunOSSiOS/OSSCompat.h>

//uPtoABYZxWxE10DX
//KaX0Nr6RvvzkA4onSCXpn2IZLJEOnO

NSString * const OSS_AccessKey = @"LTAIY6K2pDLD3pLg";
NSString * const OSS_SecretKey = @"qhigArLelVHKs8Blxx7ZL89BKlnPm5";
NSString * const OSS_endPoint = @"oss-cn-hongkong.aliyuncs.com";
NSString * const multipartUploadKey = @"multipartUploadObject";


OSSClient * client;

@implementation PKRequestTool 

static PKRequestTool *_instance;

+(instancetype)shareInstance{
    
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        if(_instance == nil)
            _instance = [[self alloc] init];
        [_instance initOSSClient];
    });
    return _instance;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        if(_instance == nil)
            _instance = [super allocWithZone:zone];
        //[_instance initOSSClient];
    });
    return _instance;
}
- (id)copyWithZone:(NSZone *)zone{
    
    return _instance;
}
#pragma mark - 初始化一个OSSClient实例
- (void)initOSSClient {
    
    // 由阿里云颁发的AccessKeyId/AccessKeySecret构造一个CredentialProvider。
    // 明文设置secret的方式建议只在测试时使用，更多鉴权模式请参考后面的访问控制章节。
    id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:OSS_AccessKey secretKey:OSS_SecretKey];
    
    OSSClientConfiguration * conf = [OSSClientConfiguration new];
    conf.maxRetryCount = 2; // 网络请求遇到异常失败后的重试次数
    conf.timeoutIntervalForRequest = 30;// 网络请求的超时时间
    conf.timeoutIntervalForResource = 24 * 60 * 60;// 允许资源传输的最长时间
    
    client = [[OSSClient alloc] initWithEndpoint:[NSString stringWithFormat:@"http://%@",OSS_endPoint] credentialProvider:credential clientConfiguration:conf];
}

#pragma mark - OSS上传文件
- (void)asyncUploadObjectWithbucketName:(NSString *)bucketName ObjectKey:(NSString *)objectKey data:(NSData *)data success:(void (^)(id, NSString *))success failure:(void (^)(NSError *))failure{
    
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    // required fields
    put.bucketName = bucketName;
    put.objectKey = objectKey;
    // 直接上传NSData
    put.uploadingData = data;
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        //        PKLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
    };
    
    OSSTask * putTask = [client putObject:put];
    
    [putTask continueWithBlock:^id(OSSTask *task) {

        if (!task.error) {

            NSString *url = [NSString stringWithFormat:@"http://%@.%@/%@",put.bucketName,OSS_endPoint,put.objectKey];
            success(task,url);
            
        } else {

            failure(task.error);
        }
        return nil;
    }];

    
}

- (void)asyncUploadObjectWithbucketName:(NSString *)bucketName ObjectKey:(NSString *)objectKey filePath:(NSString *)filePath success:(void (^)(id, NSString *))success failure:(void (^)(NSError *))failure{
    
    
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    // required fields
    put.bucketName = bucketName;
    put.objectKey = objectKey;
    // 直接上传NSData
    put.uploadingFileURL = [NSURL fileURLWithPath:filePath];
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        
    };
    
    OSSTask * putTask = [client putObject:put];
    
    [putTask continueWithBlock:^id(OSSTask *task) {
        NSLog(@"objectKey: %@", put.objectKey);
        if (!task.error) {
            NSLog(@"upload object success! -- %@",task);
            NSString *url = [NSString stringWithFormat:@"http://%@.%@/%@",put.bucketName,OSS_endPoint,put.objectKey];
            success(task,url);
            
        } else {
            NSLog(@"upload object failed, error: %@" , task.error);
            failure(task.error);
        }
        return nil;
    }];
    
}



@end
